#include <QLineF>
#include <QMenu>
#include <QDebug>
#include <QGraphicsScene>

#include "myline.h"
#include "myvex.h"

MyLine::MyLine(MyVex *s,MyVex *e,QMenu *itemMenu,QGraphicsItem *parent)
    :QGraphicsLineItem(QLineF(s->pos()+QPointF(12.5,12.5),e->pos()+QPointF(12.5,12.5)),parent)
{
    this->s = s;
    this->e = e;
    this->itemMenu = itemMenu;
    this->setZValue(-1);
    this->pen = new QPen();
    this->pen->setColor(QColor(Qt::red));
    this->pen->setWidth(3);
    this->setPen(*pen);
    s->outlines.append(this);
    e->inlines.append(this);

    QLineF l1,l2;
    l1.setP1(this->line().center());
    l2.setP1(this->line().center());
    l1.setAngle(this->line().angle()+30);
    l2.setAngle(this->line().angle()-30);
    l1.setLength(-10),l2.setLength(-10);
    arrow_1 = new QGraphicsLineItem(l1,this);
    arrow_2 = new QGraphicsLineItem(l2,this);
    arrow_1->setPen(*pen),arrow_2->setPen(*pen);

    this->setFlags(QGraphicsItem::ItemIsSelectable);
}

MyLine::~MyLine()
{  // qDebug()<<"边析构";
    delete pen;
    delete arrow_1;
    delete arrow_2;
    for(int i = s->outlines.size()-1;i > -1;i--){
        if(s->outlines[i]->e == e) s->outlines.removeAt(i);
    }
    for(int i = e->inlines.size()-1;i > -1;i--){
        if(e->inlines[i]->s == s) e->inlines.removeAt(i);
    }

}

void MyLine::UpdatePos()
{
    this->setLine(QLineF(s->pos()+QPointF(12.5,12.5),e->pos()+QPointF(12.5,12.5)));
    this->setZValue(-1);
    QLineF l1,l2;
    l1.setP1(this->line().center());
    l2.setP1(this->line().center());
    l1.setAngle(this->line().angle()+30);
    l2.setAngle(this->line().angle()-30);
    l1.setLength(-10),l2.setLength(-10);
    arrow_1->setLine(l1),arrow_2->setLine(l2);
}

void MyLine::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
    scene()->clearSelection();
    this->setSelected(true);
    itemMenu->exec(event->screenPos());
}

void MyLine::setVirtual()
{
    this->pen->setStyle(Qt::DashLine);
    this->setPen(*pen);
}

void MyLine::setSolid()
{
    this->pen->setStyle(Qt::SolidLine);
    this->setPen(*pen);
}
